package com.xuedian.xuanxuan.core.util;


import com.xuedian.xuanxuan.core.entity.JSONResult;
import net.sf.json.JSONException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by mmh on 2017/1/3.
 */
public class HtmlUtil {
    /**
     * 功能：输出json格式
     * @param response
     * @param jsonStr
     * @throws Exception
     */
    public static void writerJson(HttpServletResponse response,String jsonStr) {
        writer(response,jsonStr);
    }

    public static void writerJson(HttpServletResponse response,JSONResult jsonResult){
        try {
            response.setContentType("application/json");
            writer(response,ResultUtils.toJsonString(jsonResult));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能：输出HTML代码
     * @param response
     * @param htmlStr
     * @throws Exception
     */
    public static void writerHtml(HttpServletResponse response, String htmlStr) {
        writer(response,htmlStr);
    }

    private static void writer(HttpServletResponse response,String str){
        try {
            StringBuffer result = new StringBuffer();
            //设置页面不缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out= null;
            out = response.getWriter();
            out.print(str);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
